import { createLogger } from "../utils/logging";
import { PlatformInterface } from "./interface";

const logger = createLogger('platform/plus')

export class PlusPlatform extends PlatformInterface{
  constructor(app){
    super(app);
  }

  getKey(){
    return 'Plus'
  }

  // 是否有热更新
  getIsLiveUpdate(){
    return true;
  }

  // 热更新
  liveUpdate(resolve, dialogs){
    const dialog = dialogs.showUpdateInfo('正在下载更新包', `
    <div class="progress-bar">
      <div class="progress">
      </div>
    </div>
    <div class="textProgress">
      请求中
    </div>
    `, [])

    const progress = dialog.element.querySelector('.progress');
    const textProgress = dialog.element.querySelector('.textProgress');
    this.app.api.getWgt().then(res => {
      const wgtUrl = res.data.path;
      if(!wgtUrl){
        dialogs.showWarning('安装失败', 
          `下载wgt包失败，无法请求到正确的安装路径`
        );
        return
      }

      let download = plus.downloader.createDownload(wgtUrl, {}, (data, status) => {
        if(status == 200){
          logger.log('下载wgt包成功:', data.filename);
          textProgress.innerText = '安装中'
          
          plus.runtime.install(data.filename, {force: true}, () => {
            plus.runtime.restart();
          }, (err) => {
            logger.error('安装失败', err.code, err.message);
            const buttonSignals = dialogs.showWarning('安装失败', 
              `WGT安装包中manifest.json文件的version版本不匹配。`
            )
            
            plus.io.resolveLocalFileSystemURL(data.filename, (entry) => {     
              entry.remove(() => {  
                logger.log("删除wgt包成功");  
              }, err => {  
                logger.error("删除wgt包失败");  
              });  
            }, (e) => {  
              logger.log('wgt路径文件不存在');
            });   
  
            buttonSignals.ok.add(() => {
              resolve();
            })
          })
        } else {
          logger.warn('下载wgt包失败');
          dialogs.showWarning('安装失败', 
            `下载wgt包失败`
          );
        }
      });
  
      download.addEventListener('statechanged', task => {
        if(task.state === 3){
          progress.style.width = (task.downloadedSize / task.totalSize) * 100 + '%';
          textProgress.innerText = `${task.downloadedSize}/${task.totalSize}`;
        }
      })
  
      download.start();
    })
  }

  restart(){
    plus.runtime.restart();
  }
}